package com.sh.rbac.core.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.PrintWriter;
import java.util.Objects;

/**
 * @since 2024-04-06 13:57
 */
public class WebUtils {

    /**
     * 获取当前请求
     *
     * @return 当前请求
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }


    /**
     * 获取请求头中的 token
     *
     * @return token
     */
    public static String getToken() {
        return JwtUtils.getToken(getRequest().getHeader("Authorization"));
    }


    /**
     * 响应结果
     *
     * @param response 响应
     * @param result   结果
     */
    public static void renderString(HttpServletResponse response, Object result) {
        PrintWriter pw = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");

            // 检查是否已经调用了 response.getOutputStream()
            if (response.isCommitted()) {
                throw new IllegalStateException("getOutputStream() has already been called for this response");
            }

            pw = response.getWriter();
            pw.print(new ObjectMapper().writeValueAsString(result));
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }

}
